/*
 * 版权所有 (C) 2001-2014 深圳市艾派应用系统有限公司。保留所有权利。
 * 版本：
 * 修改记录：
 *		1、2014-7-16，tfl创建。 
 */
package com.cmcc.aregister;

import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.http.HttpAsyncTask;
import com.cmcc.aregister.ui.activity.NoticeWebView;
import cn.jpush.android.api.JPushInterface;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/*
 * 自定义极光推送通知广播。
 */
public class CustomNotifyReceiver extends BroadcastReceiver
{
    private static final String TAG = "CustomNotifyReceiver";
    protected Controller mHttpManager = null;
    private String msg_id;
    private Context context;
    protected Dialog dialog;

    @Override
    public void onReceive(Context context, Intent intent)
    {
        if (mHttpManager == null)
        {
            mHttpManager = Controller.getInstance();
        }
        this.context = context;
        Bundle bundle = intent.getExtras();
        Log.d(TAG, "[CustomNotifyReceiver] onReceive - " + intent.getAction()
            + ", extras: " + printBundle(bundle));

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction()))
        {
            String regId = bundle
                .getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "[CustomNotifyReceiver] 接收Registration Id : " + regId);

        }
        else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent
            .getAction()))
        {
            Log.d(TAG, "[CustomNotifyReceiver] 接收到推送下来的通知");

            String extras = intent.getExtras().getString(
                JPushInterface.EXTRA_EXTRA);
            try
            {
                JSONObject jsonObject = new JSONObject(extras);
                msg_id = jsonObject.getString("msg_id");
            }
            catch (JSONException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.d(TAG, "[CustomNotifyReceiver] 接收到推送下来的通知的ID: " + msg_id);
        }
        else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent
            .getAction()))
        {
            String extras = intent.getExtras().getString(
                JPushInterface.EXTRA_EXTRA);
            try
            {
                JSONObject jsonObject = new JSONObject(extras);
                msg_id = jsonObject.getString("msg_id");
            }
            catch (JSONException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // 打开自定义的Activity 跳转通告详情界面

            Log.d(TAG, "[CustomNotifyReceiver] 用户点击打开了通知" + msg_id);
            getExtraForPage();
        }
        else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent
            .getAction()))
        {
            Log.d(TAG, "[CustomNotifyReceiver] 用户收到到RICH PUSH CALLBACK: "
                + bundle.getString(JPushInterface.EXTRA_EXTRA));
            // 在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity，
            // 打开一个网页等..

        }
        else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent
            .getAction()))
        {
            boolean connected = intent.getBooleanExtra(
                JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.e(TAG, "[CustomNotifyReceiver]" + intent.getAction()
                + " connected state change to " + connected);
        }
        else
        {
            Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
        }

    }

    private HttpAsyncTask getExtraTask;

    /**
     * 获取附加信息并转跳到指定页面。
     */
    private void getExtraForPage()
    {
        JSONObject obj = new JSONObject();
        try
        {
            obj.put("request_type", Arguments.GET_EXTRAS_ACTION);
            obj.put("app_key", "c86efe809d9bb7322777056b");
            obj.put("msg_id", msg_id);
            obj.put("platform", "0");
            obj.put("phone", "");
            obj.put("channel", "medical_client");
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        showProgressDialog();
        String params = obj.toString();
        getExtraTask = new HttpAsyncTask(GlobalSetting.XML_GET_EXTRAS_TASK,
            Arguments.CLIENT_PUSH_SERVICE_URL, params,
            HttpAsyncTask.CACHE_TYPE_ACTION, true, true);
        getExtraTask.setUIHandler(getExtraTaskHandler);
        mHttpManager.execute(getExtraTask);
    }

    Handler getExtraTaskHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                if (msg.obj != null)
                {
                    Map<String, Object> map = (Map<String, Object>) msg.obj;
                    String forwordUrl = (String) map.get(Arguments.URL);
                    if (!"".equals(forwordUrl))
                    {
                        dismissProgressDialog();
                        Intent i = new Intent(context, NoticeWebView.class);
                        i.putExtra("url", forwordUrl);
                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(i);
                    }
                }
                break;
            }
        };
    };

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle)
    {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet())
        {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID))
            {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            }
            else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE))
            {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            }
            else
            {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    public void showProgressDialog()
    {
        if (dialog != null && dialog.isShowing())
        {
            return;
        }
        showProgressDialog(R.string.notice,
            context.getString(R.string.dialog_reading_info));
    }

    private void showProgressDialog(int title, String msg)
    {
        dialog = new ProgressDialog(context);
        ((ProgressDialog) dialog)
            .setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setTitle(title);
        ((ProgressDialog) dialog).setMessage(msg);
        if (null != dialog && !dialog.isShowing())
        {
            try
            {
                dialog.show();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    private void dismissProgressDialog()
    {
        if (null != dialog && dialog.isShowing())
        {
            try
            {
                dialog.dismiss();
                dialog = null;
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}
